<template>
  <el-row style="min-width: 1500px">
    <el-col :span="24">
      <div class="editor-header">
        <div class="left">
          <!-- <div v-if="show == false" @click="btnShow" style="width: 160px; margin: 0 10px">
            <div style="display: flex; align-items: center; color: #303233">
              <span>{{ name }}</span>
              <img src="../../../assets/edit.png" alt="" style="margin-left: 2px; vertical-align: middle" />
            </div>
          </div>
          <div v-if="show == true">
            <el-input type="text" maxlength="10" :autofocus="autofocus" class="borderNone" v-model="name" ref="inputRef"
              :suffix="111" @blur="blur">
              <template Slots="suffix">
                <div>
                  <img src="../../../assets/add.png" alt="" style="margin-right: 10px" />
                </div>
              </template>
            </el-input>
          </div> -->
          <div class="name">
            <div :class="{ title: autofocus, 'file-child-node': autofocus }">
              <el-text style="max-width: 100%" truncated>{{ name }} </el-text>

              <span class="--table-column-icon">
                <el-icon color="#A8ADB2" @click="editClick"
                  ><EditPen
                /></el-icon>
              </span>
            </div>

            <div>
              <input
                v-show="show"
                v-model="name"
                class="file-child-node"
                @keyup.enter="editChang"
                ref="inputRef"
                maxlength="20"
              />
            </div>
          </div>
        </div>
        <CanvasTool class="center-top" />
        <div class="right">
          <el-button @click="goBack">退出</el-button>
          <Tooltip :mouseLeaveDelay="0" title="预览">
            <div class="menu-item" @click="enterScreening()">
              <IconPreviewOpen />
              <span style="margin: 0 5px; color: #303233; font-size: 14px">
                预览
              </span>
            </div>
          </Tooltip>
          <Tooltip :mouseLeaveDelay="0" title="保存">
            <div class="menu-item" @click="open">
              <div class="bton">保存</div>
            </div>
          </Tooltip>
          <Tooltip :mouseLeaveDelay="0" title="保存">
            <div class="menu-item" @click.once="opens()">
              <div class="btn-left">保存并发布</div>
            </div>
          </Tooltip>
        </div>
        <Drawer
          width="320"
          placement="right"
          :closable="false"
          :visible="hotkeyDrawerVisible"
          @close="hotkeyDrawerVisible = false"
        >
          <HotkeyDoc />
        </Drawer>

        <!-- <FullscreenSpin :loading="exporting" tip="正在导入..." /> -->
      </div>
    </el-col>
  </el-row>
</template>

<script lang="ts" setup>
import { onMounted, ref, watch } from "vue";
import {
  getprogram,
  getscene,
  editScene,
  isExistLinkScene,
  Editprogram
} from "../../../api/advertising/index";
import { storeToRefs } from "pinia";

import { useMainStore, useSlidesStore } from "@/store";
import useScreening from "@/hooks/useScreening";
import useSlideHandler from "@/hooks/useSlideHandler";
import useHistorySnapshot from "@/hooks/useHistorySnapshot";
import useImport from "@/hooks/useImport";
import CanvasTool from "../CanvasTool/index.vue";
import HotkeyDoc from "./HotkeyDoc.vue";
import FileInput from "@/components/FileInput.vue";
import { Calendar, Search, EditPen } from "@element-plus/icons-vue";
import FullscreenSpin from "@/components/FullscreenSpin.vue";
import { ElInput, ElMessage } from "element-plus";
import { Tooltip, Dropdown, Menu, Drawer } from "ant-design-vue";
import { useRoute, useRouter } from "vue-router";
const router = useRouter();
const route = useRoute();
import { Log } from "@icon-park/vue-next";
import { isObject } from "lodash";
const MenuItem = Menu.Item;
import { fillDigit } from "@/utils/common";
const mainStore = useMainStore();
const { gridLineSize, showRuler, showSelectPanel, sharedData, eventIs } =
  storeToRefs(mainStore);
const { enterScreening, enterScreeningFromStart } = useScreening();
const { createSlide, deleteSlide, resetSlides } = useSlideHandler();
const { redo, undo } = useHistorySnapshot();
const { importSpecificFile, importPPTXFile, exporting } = useImport();
var name = ref("");
const inputRef = ref();
var autofocus = ref(false);
const setDialogForExport = mainStore.setDialogForExport;
const { slides, slideIndex, currentSlide } = storeToRefs(useSlidesStore());
const slidesStore = useSlidesStore();
var sharedDatas = ref("");
// slidesStore.$reset()
// resetSlides()
slides.value.forEach((v: any) => {
  deleteSlide(v.id);
});

slidesStore.addSlide({
  id: "test-slide-1",
  elements: [],
  background: {
    type: "solid",
    color: "#FFFFFFFF",
  },
  sceneSize: "",
  sceneTime: "10",
  sceneName: "",
});

const open = async () => {
  eventIs.value++;
  //   setTimeout(() => {

  //   }, 200);

  // 遍历每个 slide
  slides.value.forEach((slide, index) => {
    let addsre = fillDigit(index + 1, 2);
    let adre = "场景000000" + addsre;
    slides.value.map((a, e) => {
      if (index == e) {
        a.sceneName = adre;
      }
    });

    // 获取当前 slide 的 elements 数组
    const elements = slide.elements;

    // 遍历每个元素
    elements.forEach((element) => {
      // 如果当前元素的类型为 item，则进行修改
      if (element.type === "time") {
        element.content = mainStore.timeInfo;
        element.style = mainStore.style;
      }
    });
  });
  const totalFileSize = slides.value.reduce((acc, obj) => {
    if (obj.hasOwnProperty("elements")) {
      obj.elements.forEach((element) => {
        if (element.hasOwnProperty("fileSize")) {
          acc += element.fileSize;
        }
      });
    }
    if (obj.hasOwnProperty("turningMode")) {
      obj.turningMode.forEach((turningMode) => {
        if (turningMode.hasOwnProperty("fileSize")) {
          acc += turningMode.fileSize;
        }
      });
    }
    if (obj.hasOwnProperty("fileSize")) {
      acc += obj.fileSize;
    }
    return acc;
  }, 0);
  var time: any = ref([]);
  let arr = slides.value.map((a) => a.sceneTime).join();

  time.value = arr.replace(",", ", ");
  slides.value.filter((a) => {
    a.sceneSize = totalFileSize;
  });

  var content = ref([]);
  slides.value.map((idet, index) => {});

  // 保存第一个场景的turningMode，并删除其他场景的turningMode
  const firstTurningMode = slides.value[0]?.turningMode || [];
  slides.value.forEach((scene: any, index: number) => {
    if (index !== 0) {
      scene.turningMode = [];
    }
  });
  slides.value[0].turningMode = firstTurningMode;

  content.value = JSON.stringify(slides.value);
  const linkProgram = route.query.id
    ? route.query.id
    : localStorage.getItem("id");
  var filteredSlides = slides.value.map(
    ({ sceneSize, sceneTime, sceneName }) => ({
      sceneSize,
      sceneTime: sceneTime ? sceneTime : "10",
      sceneName,
      linkProgram,
    })
  );
  // 遍历给定数组中的每个对象
  slides.value.forEach((givenObj) => {
    filteredSlides.map((person) => ({
      ...person,
      content: "",
    }));
    // 找到目标数组中sceneName属性与当前给定对象相同的对象
    filteredSlides.find(
      (targetObj) => targetObj.sceneName === givenObj.sceneName
    );
    let givenObjs = givenObj.elements.map((item: any) => {
      if (item.type == "text") {
        item.content = item.content.replace(/<\/?[a-z][^>]*>/gi, "");

        return item;
      }
    });

    filteredSlides.map((a) => {
      if (a.sceneName === givenObj.sceneName)
        a.content = JSON.stringify(givenObj);
    });
  });

  let data = ref<any>(filteredSlides);
  var adds = ref();
  adds.value = data.value.map((item: any) => {
    let parsedContent = JSON.parse(item.content);
    if (parsedContent.elements) {
      parsedContent.elements = parsedContent.elements.map((val: any) => {
        val.left = parseFloat(val.left ? val.left : (0).toFixed(1));
        val.left = parseFloat(val.top ? val.top : (0).toFixed(1));
        val.left = parseFloat(val.width ? val.width : (0).toFixed(1));
        val.left = parseFloat(val.height ? val.height : (0).toFixed(1));
        return val;
      });
      return parsedContent;
    }
  });

  var addList = ref();
  addList.value = data.value.map((add: any) => {
    add.content = JSON.stringify(add.content);
    return add;
  });

  // setDialogForExport("pptx");
  let sceneDTOList = {
    sceneDTOList: addList.value,
    thumbnail: sharedData.value,
    programId: route.query.id ? route.query.id : "",
  };

  let thumbnail = {
    thumbnail: sharedData.value,
  };
  // return
  // 修改
  // let res = await editScene(sceneDTOList);
  // 新增
  // let res = await getscene(sceneDTOList);

  sceneDTOList.sceneDTOList.linkProgram = route.query.id;
  let res = route.query.id
    ? await editScene(sceneDTOList)
    : await getscene(sceneDTOList);
  if (res.data.code == 1) {
    ElMessage({ message: res.data.msg, type: "success", duration: 1000 });
  } else {
    ElMessage({ message: res.data.msg, type: "error", duration: 1000 });
  }
};
const opens = async () => {
  eventIs.value++;
  //   setTimeout(() => {

  //   }, 200);

  // 遍历每个 slide
  slides.value.forEach((slide, index) => {
    let addsre = fillDigit(index + 1, 2);
    let adre = "场景000000" + addsre;
    slides.value.map((a, e) => {
      if (index == e) {
        a.sceneName = adre;
      }
    });

    // 获取当前 slide 的 elements 数组
    const elements = slide.elements;

    // 遍历每个元素
    elements.forEach((element) => {
      // 如果当前元素的类型为 item，则进行修改
      if (element.type === "time") {
        element.content = mainStore.timeInfo;
      }
    });
  });

  const totalFileSize = slides.value.reduce((acc, obj) => {
    if (obj.hasOwnProperty("elements")) {
      obj.elements.forEach((element) => {
        if (element.hasOwnProperty("fileSize")) {
          acc += element.fileSize;
        }
      });
    }
    if (obj.hasOwnProperty("turningMode")) {
      obj.turningMode.forEach((turningMode) => {
        if (turningMode.hasOwnProperty("fileSize")) {
          acc += turningMode.fileSize;
        }
      });
    }
    if (obj.hasOwnProperty("fileSize")) {
      acc += obj.fileSize;
    }
    return acc;
  }, 0);
  var time: any = ref([]);
  let arr = slides.value.map((a) => a.sceneTime).join();

  time.value = arr.replace(",", ", ");
  slides.value.filter((a) => {
    a.sceneSize = totalFileSize;
  });

  var content = ref([]);
  slides.value.map((idet, index) => {});

  content.value = JSON.stringify(slides.value);
  const linkProgram = route.query.id
    ? route.query.id
    : localStorage.getItem("id");
  var filteredSlides = slides.value.map(
    ({ sceneSize, sceneTime, sceneName }) => ({
      sceneSize,
      sceneTime: sceneTime ? sceneTime : "10",
      sceneName,
      linkProgram,
    })
  );
  // 遍历给定数组中的每个对象
  slides.value.forEach((givenObj) => {
    filteredSlides.map((person) => ({
      ...person,
      content: "",
    }));
    // 找到目标数组中sceneName属性与当前给定对象相同的对象
    filteredSlides.find(
      (targetObj) => targetObj.sceneName === givenObj.sceneName
    );
    let givenObjs = givenObj.elements.map((item: any) => {
      if (item.type == "text") {
        item.content = item.content.replace(/<\/?[a-z][^>]*>/gi, "");

        return item;
      }
    });

    filteredSlides.map((a) => {
      if (a.sceneName === givenObj.sceneName)
        a.content = JSON.stringify(givenObj);
    });
  });

  let data = ref<any>(filteredSlides);
  var adds = ref();
  adds.value = data.value.map((item: any) => {
    let parsedContent = JSON.parse(item.content);
    if (parsedContent.elements) {
      parsedContent.elements = parsedContent.elements.map((val: any) => {
        val.left = parseFloat(val.left ? val.left : (0).toFixed(1));
        val.left = parseFloat(val.top ? val.top : (0).toFixed(1));
        val.left = parseFloat(val.width ? val.width : (0).toFixed(1));
        val.left = parseFloat(val.height ? val.height : (0).toFixed(1));
        return val;
      });
      return parsedContent;
    }
  });

  var addList = ref();
  addList.value = data.value.map((add: any) => {
    add.content = JSON.stringify(add.content);
    return add;
  });

  // setDialogForExport("pptx");
  let sceneDTOList = {
    sceneDTOList: addList.value,
    thumbnail: sharedData.value,
    programId: route.query.id ? route.query.id : "",
  };

  let thumbnail = {
    thumbnail: sharedData.value,
  };
  // return
  // 修改
  // let res = await editScene(sceneDTOList);
  // 新增
  // let res = await getscene(sceneDTOList);
  sceneDTOList.sceneDTOList.linkProgram = route.query.id;
  let res = route.query.id
    ? await editScene(sceneDTOList)
    : await getscene(sceneDTOList);
  if (res.data.code == 1) {
    ElMessage({ message: res.data.msg, type: "success", duration: 1000 });
  } else {
    ElMessage({ message: res.data.msg, type: "error", duration: 1000 });
  }
};
const programId = ref();
const goBack = async () => {
  let res = await isExistLinkScene(programId.value);
  if (res.data.data == true) {
    router.go(-1);
  } else {
    ElMessage({ message: "请保存之后再退出", type: "error", duration: 1000 });
  }
};
const toggleGridLines = () => {
  mainStore.setGridLineSize(gridLineSize.value ? 0 : 50);
};
var show = ref(false);
const btnShow = () => {
  show.value = true;
  autofocus.value = true;
};
const blur = () => {
  show.value = false;
  autofocus.value = false;
};
const toggleRuler = () => {
  mainStore.setRulerState(!showRuler.value);
};

const openSelectPanel = () => {
  if (!showSelectPanel.value) mainStore.setSelectPanelState(true);
  else mainStore.setSelectPanelState(false);
};

const hotkeyDrawerVisible = ref(false);
var autofocus = ref(false);
var dataInfo = ref()
const editChang = async () => {
  show.value = false;
  autofocus.value = false;
  let data={
    programName:name.value,
    objectVersionNumber:dataInfo.value.objectVersionNumber,
    id:dataInfo.value.id
  }
  let result = await Editprogram(data)
  if(result.data.code==1){
    ElMessage({ message: result.data.msg, type: "success", duration: 1000 })
    // 节目名称
  let res = await getprogram(
    route.query.id ? route.query.id : localStorage.getItem("id")
  );
  name.value = res.data.data.programName;
  programId.value = res.data.data.id;
  dataInfo.value = res.data.data;
  mainStore.canvasHeight1 = res.data.data.longResolution;
  mainStore.canvasWidth1 = res.data.data.wideResolution;
  }else{
    ElMessage({ message: result.data.msg, type: "error", duration: 1000 })
  }
  
};
const editClick = () => {
  inputRef.value.focus();
  show.value = true;
  autofocus.value = true;
};
onMounted(async () => {
  // 节目名称
  let res = await getprogram(
    route.query.id ? route.query.id : localStorage.getItem("id")
  );
  name.value = res.data.data.programName;
  programId.value = res.data.data.id;
  dataInfo.value = res.data.data;
  mainStore.canvasHeight1 = res.data.data.longResolution;
  mainStore.canvasWidth1 = res.data.data.wideResolution;
});
</script>
<style lang="scss" scoped>
.name {
  display: flex;
    height: 26px;
  .title {
    border: 1px solid #ebeff3;
    border-radius: 4px;
    width: 150px;
    height: 26px;
    line-height: 26px;
    text-align: center;
    display: flex;
    justify-content: space-between;
    padding: 0 5px;
  }
  .--table-column-icon {
    line-height: 26px;
    cursor: pointer;
  }
}
::v-deep .el-col-24 {
    max-width: 100%;
    flex: 0 0 100%;
    /* height: 50px; */
    border-bottom: 1px solid #f6f7f9;
}
::v-deep .el-input__wrapper {
  display: inline-flex;
  flex-grow: 1;
  align-items: center;
  justify-content: center;
  padding: 1px 11px;
  // background-color: var(--el-input-bg-color, var(--el-fill-color-blank));
  background-image: none;
  transition: var(--el-transition-box-shadow);
  transform: translate3d(0, 0, 0);
  // box-shadow: 0 0 0 1px #fff;
}

::v-deep .el-input {
  --el-input-text-color: var(--el-text-color-regular);
  --el-input-border: var(--el-border);
  --el-input-hover-border: var("");
  /* --el-input-focus-border: var(--el-color-primary); */
  --el-input-transparent-border: 0 0 0 1px transparent inset;
  --el-input-border-color: var(--el-border-color);
  --el-input-border-radius: var(--el-border-radius-base);
  --el-input-bg-color: var(--el-fill-color-blank);
  --el-input-icon-color: var(--el-text-color-placeholder);
  --el-input-placeholder-color: var(--el-text-color-placeholder);
  --el-input-hover-border-color: var(--el-border-color-hover);
  --el-input-clear-hover-color: var(--el-text-color-secondary);
  --el-input-focus-border-color: "";
}
.file-child-node {
  width: 150px !important;
  height: 26px !important;
  color: #303233; /* 修改输入文本的颜色 */
  background-color: #ebeff3; /* 修改背景色 */
  border: 1px solid #ebeff3; /* 修改边框样式 */
  border-radius: 4px;
  padding: 0 5px;
  margin-right: 15px;
  /* 添加其他样式属性 */
}
.file-child-node:focus {

outline:none;

    border: 1px solid #0DAEFF;

}
::v-deep .custom-input .el-input__inner:focus {
  border-color: initial !important;
  height: initial !important;
}
::v-deep .el-input__wrapper:focus {
  border-color: #333 !important;
  box-shadow: none;
  background-color: none;
  height: auto;
}
::v-deep .el-input__wrapper :focus {
  box-shadow: 0 0 0 1px #ccc;
  background-color: #fff;
  border-color: #ccc !important;
  border-radius: 4px;
  width: 150px;
  height: 25px;
  padding: 1px 11px;
  margin-left: -10px;
}

.btn-left {
  background-color: #0daeff;
  border: 1px solid #0daeff;
  height: 35px;
  width: 100px;
  line-height: 35px;
  text-align: center;
  border-radius: 4px;
  color: #fff;
}

.bton {
  background-color: #fff;
  border: 1px solid #0daeff;
  height: 35px;
  width: 60px;
  line-height: 35px;
  text-align: center;
  border-radius: 4px;
  color: #0daeff;
}

.editor-header {
  background-color: #fff;
  user-select: none;
  // border-bottom: 1px solid $borderColor;
  display: flex;
  justify-content: space-between;
  padding: 0 5px;
  height: 50px;
}

.left,
.right {
  display: flex;
  justify-content: center;
  align-items: center;
}
::v-deep input[type="text"], input[type="password"], textarea {
  border-color: red; /* 修改边框颜色 */
}
.menu-item {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 14px;
  padding: 0 10px;
  cursor: pointer;

  .text {
    margin-left: 4px;
  }
}

.layout-header {
  height: 50px;
}

.left .menu-item:hover {
  background-color: #f9f9f9;
}
</style>
